package com.alibaba.nacos.naming.remote.rpc.handler;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.remote.NamingRemoteConstants;
import com.alibaba.nacos.api.naming.remote.request.InstanceRequest;
import com.alibaba.nacos.api.naming.remote.response.InstanceResponse;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.core.v2.service.ClientOperationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class InstanceRequestHandler
        extends RequestHandler<InstanceRequest, InstanceResponse> {

    private final ClientOperationService clientOperationService;

    @Override
    public InstanceResponse handle(InstanceRequest request,
                                   RequestMeta meta) throws NacosException {
        Service service = Service.newService(request.getNamespace(), request.getGroupName(), request.getServiceName(), true);
        switch (request.getType()) {
            case NamingRemoteConstants.REGISTER_INSTANCE:
                return registerInstance(service, request, meta);
            case NamingRemoteConstants.DE_REGISTER_INSTANCE:
                return deregisterInstance(service, request, meta);
            default:
                throw new UnsupportedOperationException();
        }
    }

    private InstanceResponse registerInstance(Service service,
                                              InstanceRequest request,
                                              RequestMeta meta) throws NacosException {
        clientOperationService.registerInstance(service, request.getInstance(), meta.getConnectId());
        return new InstanceResponse(NamingRemoteConstants.REGISTER_INSTANCE);
    }

    private InstanceResponse deregisterInstance(Service service,
                                                InstanceRequest instanceRequest,
                                                RequestMeta meta) {
        clientOperationService.deregisterInstance(service, instanceRequest.getInstance(), meta.getConnectId());
        return new InstanceResponse(NamingRemoteConstants.DE_REGISTER_INSTANCE);
    }
}
